import { Button, message, Modal } from 'antd';
import React, { useState, useRef, useEffect, useContext } from 'react';
import ProTable from '@ant-design/pro-table';
import UpdateForm from './components/UpdateForm';
import {
  queryList,
  queryCarDetail,
  getGroupList,
  updateCarState,
  updateCar,
  updateCarList,
} from './service';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { UserContext } from '@/layouts/UserProvider';

const TableList = () => {
  const [groupList, setGroupList] = useState();
  const [updateModalVisible, handleDetailModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [type, setType] = useState('');
  const actionRef = useRef();
  const userCtx = useContext(UserContext);
  const permits = userCtx.userPermits;
  console.log('!!!!!!!!!!!!!!!!!!!!!permits: ' + permits);
  const handleEdit = async (fields) => {
    const hide = message.loading('正在修改');
    try {
      await updateCar({
        available_status: fields.available_status,
        car_id: fields.car_id,
      });
      hide();
      if (code == '200') {
        message.success('修改成功');
        handleDetailModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error('修改失败请重试！');
      }
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
    }
  };

  //更改预约状态
  const handleFun = async (params) => {
    const hide = message.loading('正在修改');
    try {
      const res = await updateCarState(params);
      hide();
      if (res.code == '200') {
        message.success('修改成功');
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error('修改失败请重试！');
        return false;
      }
      return true;
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      return false;
    }
  };

  const handleUpdateList = async (fields) => {
    const hide = message.loading('正在更新');
    try {
      const res = await updateCarList();
      hide();
      if (res.code == '200') {
        message.success('更新成功');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      } else {
        message.error('更新失败请重试！');
        return false;
      }
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };

  useEffect(() => {
    getGroupList().then((data) => {
      let result = data?.data;
      let list = {};
      if (result && result.length > 0) {
        result.forEach((item, i) => {
          list[item.group] = { text: item.group, status: item.group };
        });
        setGroupList(list);
      }
    });
  }, []);
  //更改状态
  const handleUpdateStatus = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要修改状态？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleFun({
          car_id: record.car_id,
          available_status: record.available_status == 1 ? 2 : 1,
        }).then((data) => {});
        console.log(record.car_id);
      },
    });
  };
  const columns = [
    {
      title: '车辆ID',
      search: false,
      dataIndex: 'car_id',
    },
    {
      title: '车牌号',
      search: false,
      dataIndex: 'card',
    },
    {
      title: '车型',
      search: false,
      dataIndex: 'car_type',
    },
    {
      title: '部门',
      dataIndex: 'group',
      search: false,
    },
    {
      title: '所属部门',
      dataIndex: 'group',
      hideInTable: true,
      hideInForm: true,
      valueEnum: groupList,
    },
    {
      title: '所在地',
      search: false,
      dataIndex: 'location',
      hideInForm: true,
    },
    {
      title: '可否预约',
      search: false,
      dataIndex: 'available_status',
      hideInForm: true,
      render: (available_status) => <>{available_status == 1 ? '是' : '否'}</>,
    },
    {
      title: '车辆硬件配置',
      dataIndex: 'is_profiles',
      hideInTable: true,
      hideInForm: true,
      valueEnum: {
        0: {
          text: '相机',
          status: '',
          dataIndex: 'cam',
        },
        1: {
          text: 'Radar',
          dataIndex: 'radar',
          status: '',
        },
        2: {
          text: 'Lidar',
          status: '',
          dataIndex: 'lidar',
        },
        3: {
          text: 'Other sensors',
          status: '',
        },
      },
      render: (is_profiles) => <>{is_profiles}</>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let res = [];
        if (permits.includes('detailCar')) {
          res.push(
            <Button
              size="small"
              key="search"
              onClick={() => {
                try {
                  queryCarDetail({ car_id: record.car_id }).then((res) => {
                    if (res.code == '200') {
                      handleDetailModalVisible(true);
                      setStepFormValues(res.data);
                      setType(2);
                    }
                  });
                } catch (error) {
                  console.log('error: ' + error);
                }
              }}
            >
              查看
            </Button>,
          );
        }
        if (permits.includes('updateCar')) {
          res.push(
            <Button
              size="small"
              key="search"
              onClick={() => {
                handleUpdateStatus(record);
              }}
            >
              {record.available_status == 1 ? '禁止预约' : '启动预约'}
            </Button>,
          );
        }
        return res;
      },
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={{
          collapsed: false,
          defaultCollapsed: false,
          collapseRender: () => '',
          labelWidth: 120,
          searchText: '搜索',
        }}
        request={async (params, sorter, filter) => {
          try {
            params.is_total = true;
            params.limit = params.pageSize;
            params.offset = (params.current - 1) * params.pageSize;
            const res = await queryList({ ...params, sorter, filter });
            return {
              data: JSON.stringify(res.data) != '{}' ? res.data : [],
              success: true,
              total: res.total || 0,
            };
          } catch (error) {
            return { data: [], success: false, total: 0 };
          }
        }}
        columns={columns}
        toolBarRender={() => {
          let res = [];
          if (permits.includes('syncCar')) {
            res.push(
              <Button
                type="primary"
                key="primary"
                onClick={() => {
                  return handleUpdateList();
                }}
              >
                更新数据
              </Button>,
            );
          }
          return res;
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize: 10,
        }}
      />
      <UpdateForm
        onSubmit={async (value) => {
          //编辑
          if (type == 1) {
            await handleEdit(value);
          }
        }}
        onCancel={() => {
          handleDetailModalVisible(false);
        }}
        type={type}
        updateModalVisible={updateModalVisible}
        values={stepFormValues}
      />
    </>
  );
};

export default TableList;
